package net.cgsoft.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.TextView;


/**
 * Created by Youga on 2015/12/25.
 */
public class ItemDialogFragment extends DialogFragment {


    public static final String TAG = "ItemDialogFragment";
    private ItemDialogFragmentCallBack callBack;

    public static ItemDialogFragment newInstance(ItemDialogFragmentCallBack callBack,
                                                 String title, String[] items) {
        ItemDialogFragment fragment = new ItemDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putStringArray("items", items);
        fragment.setArguments(bundle);
        fragment.setAlertDialogFragmentCallBack(callBack);
        return fragment;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        String title = bundle.getString("title");
        String[] items = bundle.getStringArray("items");
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);
        builder.setTitle(title).setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                callBack.onClick(dialog, which);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                callBack.onClick(dialog, which);
            }
        });
        AlertDialog dialog = builder.show();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metric = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metric);
        lp.width = (int) (metric.widthPixels - 50 * metric.density);
        dialog.getWindow().setAttributes(lp);
        return dialog;
    }

    public interface ItemDialogFragmentCallBack {
        void onClick(DialogInterface dialog, int which);
    }

    public void setAlertDialogFragmentCallBack(ItemDialogFragmentCallBack callBack) {
        this.callBack = callBack;
    }
}
